import time


# 读取用户信息文件：file_path (str): 用户信息文件路径
def read_user_info(file_path):

    with open(file_path, "r") as file:
        lines = file.readlines()
    users = {}
    for line in lines:
        parts = line.strip().split(" ")  # 按空格分割用户名 密码 错误次数 最后错误时间
        username = parts[0]
        password = parts[1]
        error_count = int(parts[2])
        last_error_time = float(parts[3])
        users[username] = {
            "password": password,
            "error_count": error_count,
            "last_error_time": last_error_time,
        }
    return users


# 将用户信息写回文件：file_path (str): 目标文件路径；users (dict): 需要保存的用户信息字典
def write_user_info(file_path, users):

    with open(file_path, "w") as file:
        for username, info in users.items():
            # 按固定格式写入每行数据
            file.write(
                f"{username} {info['password']} {info['error_count']} {info['last_error_time']}\n"
            )


# 用户登录验证主流程：file_path (str): 用户信息存储文件路径
def main(file_path):
    users = read_user_info(file_path)

    while True:
        username = input("请输入用户名: ")
        if username not in users:
            print("用户不存在。")
            continue

        user_info = users[username]

        # 账户冻结检测逻辑
        if user_info["error_count"] >= 4:
            current_time = time.time()
            if current_time - user_info["last_error_time"] > 86400:  # 24小时时间戳差
                # 自动解冻并重置错误计数
                user_info["error_count"] = 0
                user_info["last_error_time"] = 0
                write_user_info(file_path, users)
                print("账户已解冻，请重新输入密码。")
            else:
                print("账户已被冻结，请24小时后再试。")
                continue

        password = input("请输入密码: ")

        if password == user_info["password"]:
            print("欢迎登录！")
            # 登录成功后重置错误计数
            user_info["error_count"] = 0
            user_info["last_error_time"] = 0
            write_user_info(file_path, users)
            break
        else:
            # 更新错误计数和最后错误时间
            user_info["error_count"] += 1
            user_info["last_error_time"] = time.time()
            write_user_info(file_path, users)
            remaining = 4 - user_info["error_count"]
            print(
                f"密码错误，您还有{remaining}次机会。"
                if remaining > 0
                else "密码错误，账户已冻结！"
            )


if __name__ == "__main__":
    file_path = "user_inf.txt"  # 用户信息存储文件路径
    main(file_path)
